// pages/test/test.js
var app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		id:'',//活动id
		userid:null,//渠道id
		list: [],
		showList: [],
		indicatorDots: false,
		vertical: false,
		autoplay: false,
		circular: false,
		interval: 2000,
		duration: 500,
		userInfo: '',
		ficationId: '',
		openId: '',
		isIphoneX: '',
		videoFlag: false,
		swiperCurrent: 0,
		searchArray: ['公司品牌', '公司名称'],
		searchIndex: 0,
		goodsId_Arr: [],
		page: 1, //当前页码
		curr: 0, //当前索引
		totalCount: 0, //数据总数
		show:false,
	},
	//关闭评论
	onClose() {
	    this.setData({ show: false });
	},
	//打开评论列表
	commentOpen:function(e){
		console.log('点击打开评论列表')
		this.setData({
			show:true
		})
	},
	like: function(e) {
		var _this = this;

		var temp = _this.data.list;
		const cid = _this.data.list[e.currentTarget.dataset.id].did;
		console.log('_this.data.likeflag', temp[e.currentTarget.dataset.id].likeTag)
		if (!temp[e.currentTarget.dataset.id].likeTag) {
			temp[e.currentTarget.dataset.id].like++;
			wx.request({
				url: app.globalData.url+'/v1/goods/like',
				method: 'POST',
				data: {
					cid: cid,
					openid: app.globalData.openId
				},
				success: function(r) {
					console.log(r);
				}
			})
			temp[e.currentTarget.dataset.id].likeFormat = _this.likeFormat(temp[e.currentTarget.dataset.id].like);
			temp[e.currentTarget.dataset.id].likeTag = true;
		} else {
			temp[e.currentTarget.dataset.id].like--;
			wx.request({
				url: app.globalData.url+'/v1/goods/cancel',
				method: 'POST',
				data: {
					cid: cid,
					openid: app.globalData.openId
				},
				success: function(r) {
					console.log(r);
				}
			})
			temp[e.currentTarget.dataset.id].likeFormat = _this.likeFormat(temp[e.currentTarget.dataset.id].like);
			temp[e.currentTarget.dataset.id].likeTag = false;
		}

		this.setData({
			list: temp
		})
	},
	likeFormat(number) {
		if (number < 99999 && number > 9999) {
			return number.toString().slice(0, 1) + '.' + number.toString().slice(1, 2) + 'W';
		} else if (number < 999999 && number > 99999) {
			return number.toString().slice(0, 2) + '.' + number.toString().slice(2, 4) + 'W';
		} else if (number < 9999999 && number > 999999) {
			return number.toString().slice(0, 3) + '.' + number.toString().slice(3, 4) + 'W';
		} else if (number < 99999999 && number > 9999999) {
			return number.toString().slice(0, 4) + '.' + number.toString().slice(4, 5) + 'W';
		} else if (number < 999999999 && number > 99999999) {
			return number.toString().slice(0, 5) + '.' + number.toString().slice(5, 6) + 'W';
		} else if (number < 9999999999 && number > 999999999) {
			return number.toString().slice(0, 6) + '.' + number.toString().slice(6, 7) + 'W';
		}
		return number;
	},
	search() {
		wx.navigateTo({
			url: '/pages/search/search'
		})
	},
	//切换swiper
	swiperChange: function(e) {
		//console.log('swiper切换了------',e)
		console.log(`current===${e.detail.current},this.data.list.length===${this.data.list.length}`)
		if (e.detail.current == this.data.list.length - 2) { //当切换到倒数第二个时请求加载新列表
			if (e.detail.current > this.data.curr) {
				this.data.curr = e.detail.current
				if (Math.ceil(this.data.totalCount / 5) > this.data.page) {
					this.data.page++
					this.getList()
				} else {
					this.setData({
						circular: true
					})
				}

			}

		}
		var idx = Number(e.detail.currentItemId)
		var v
		this.setData({
			videoFlag: false,
		})
		app.globalData.ficationLOGO = this.data.list[idx].lurl
		for (let i = 0; i < this.data.list.length; i++) {
			v = wx.createVideoContext('v' + i)
			v.seek(0)
			v.pause()
		}

		if (this.data.goodsId_Arr.indexOf(this.data.list[idx].cid) === -1) {
			const temp = this.data.goodsId_Arr;
			temp.push(this.data.list[idx].cid);
			this.setData({
				goodsId_Arr: temp
			})
		}

		// wx.createVideoContext('v' + idx).play()
	},

	goodSee() {
		var _this = this;
		console.log(_this.data.goodsId_Arr);
		wx.request({
			url: app.globalData.url+'/v1/goods/see',
			method: 'POST',
			data: {
				cid: _this.data.goodsId_Arr.join(),
				openid: app.globalData.openId
			},
			success: function(r) {
				console.log(r);
				if (r.data.code == 0)
					_this.getList();
			}
		})
	},
	scrollEnd: function(e) {
		var idx = Number(e.detail.currentItemId)
		var list = this.data.list
		if (idx != 0 && idx != list.length - 1) {
			list.map(item => {
				item.isShow = false
				return item
			})
			list[idx].isShow = true
			list[idx + 1].isShow = true
			list[idx - 1].isShow = true
			this.setData({
				list: list,
			})
		}
		wx.createVideoContext('v' + idx).play()
	},
	videoClick: function(e) {
		let index = e.currentTarget.dataset.index
		let v = wx.createVideoContext('v' + index)
		if (this.data.videoFlag) {
			v.play()
			this.setData({
				videoFlag: false
			})
		} else {
			v.pause()
			this.setData({
				videoFlag: true
			})
		}
	},
	goPage: app.goPage,
	getUser: function(r) {
		console.log('id-------------------', r.currentTarget.dataset.id)
		var _this = this
		if (r.detail.errMsg == 'getUserInfo:ok') {
			app.globalData.userInfo = r.detail.userInfo
			this.setData({
				userInfo: r.detail.userInfo
			})
			wx.request({
				url: app.globalData.url+'/v1/wechat/user',
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				data: {
					nikname: r.detail.userInfo.nickName,
					headimgurl: r.detail.userInfo.avatarUrl,
					openid: app.globalData.openId
				},
				success: function(res) {
					if (res.data.code == 0) {
						wx.navigateTo({
							url: '/pages/goodsDetail/goodsDetail?fid=' + r.currentTarget.dataset.id+'&activity='+_this.data.id+'&ffid=15'
						})
					} else {
						wx.showToast({
							title: '获取信息失败',
							icon: 'none',
							duration: 2000
						})
					}
				}
			})
		}
	},
	getList: function() {
		var _this = this
		if (_this.data.page == 1) {
			wx.showToast({
				icon: 'loading',
				title: 'loading...',
				duration: 60000,
				mask: true
			})
		}
		if(_this.data.id){
			wx.request({
				url: app.globalData.url+'/v1/channel/channel',
				method: 'GET',
				data: {
					id:_this.data.id,
					//id:4,
					size: '5',
					page: _this.data.page,
					openid: app.globalData.openId
				},
				success: function(r) {
					console.log(r);
					if(r.data.data.items.length>0){
						const temp = r.data.data.items.map((item, index) => {
							if (index == 0 || index == 1) {
								item.isShow = true
							} else {
								item.isShow = false
							}
							/* item.gprice = Math.ceil(item.gprice) */
							item.likeFormat = _this.likeFormat(item.like);
							item.likeTag = r.data.data.like.some(res => {
								return res.detail_id === item.detail_id;
							});
						
							return item
						})
						if (_this.data.page == 1) {
							app.globalData.ficationLOGO = temp[0].lurl
							_this.setData({
								goodsId_Arr: [temp[0].cid],
								list: temp,
								totalCount: r.data.data.pages.totalCount
							})
						} else {
							_this.setData({
								list: _this.data.list.concat(temp)
							})
						}
					}
					console.log('_this.data.list--------', _this.data.list)
					wx.hideToast()
				}
			})
		}else{
			wx.showToast({
				icon:'none',
				title: '当前暂无活动',
				duration: 3000,
				mask: true
			})
		}
	},
	getMobile: function() {
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/payment/show',
			method: 'GET',
			data: {
				openid: app.globalData.openId
			},
			success: function(r) {
				r = r.data
				if (r.code == 0) {
					app.globalData.mobile = r.data.user.mobile
				} else {
					wx.showToast({
						title: r.data.message,
						icon: 'none',
						duration: 2000
					})
				}
			}
		})
	},
	follow: function() {
		wx.showToast({
			title: '敬请期待',
			icon: 'none'
		})
	},
	getQueryString: function(url, name) {
		var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
		var r = url.substr(1).match(reg)
		if (r != null) {
			return r[2]
		}
		return null
	},
	getCoupon: function(options) {
		const _this = this
		if (options.q) {
			var q = decodeURIComponent(options.q)
			console.log("index 生命周期 onload url=" + q)
			console.log("index 生命周期 onload 参数 userid=" + _this.getQueryString(q, 'userid'))
			console.log("index 生命周期 onload 参数 id=" + _this.getQueryString(q, 'id'))
			var userid = _this.getQueryString(q, 'userid')
			var id = _this.getQueryString(q, 'id')
			console.log(userid)
			_this.setData({
				userid: userid,
				id:id
			})
			_this.recordingUser(_this.data.userid,_this.data.openId)
		}
	},
	//记录用户归属
	recordingUser:function(id,openid){
		wx.request({
			url: app.globalData.url+'/v1/channel/modify',
			method: 'POST',
			data: {
				id:id,
				openid:openid
			},
			success: function(r) {
				console.log('记录用户归属--------');
				console.log(r);
			}
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log('options-------', JSON.stringify(options))
		var _this = this
		
		var isIphoneX = app.globalData.isIphoneX;
		this.setData({
			isIphoneX: isIphoneX
		})
		console.log(this.data.isIphoneX)
		wx.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#ffffff'
		})
		// 登录
		wx.login({
			success: res => {
				// 发送 res.code 到后台换取 openId, sessionKey, unionId
				wx.request({
					url: app.globalData.url+'/v1/wechat/accesstoken',
					method: 'get',
					data: {
						code: res.code
					},
					success: function(r) {
						console.log(r)
						if (r.data.code === 0) {
							app.globalData.session_key = r.data.data.session_key
							app.globalData.openId = r.data.data.openid
							_this.setData({
								openId: r.data.data.openid
							})
							_this.getCoupon(options)
							_this.getList()
							_this.getMobile()
							console.log(app.globalData.session_key)
							console.log(app.globalData.openId)
						} else {
							wx.showToast({
								title: '获取信息失败',
								icon: 'none',
								duration: 2000
							})
						}
					}
				})
			}
		})
		// setTimeout(function(){
		// wx.createVideoContext('v0').play()
		// }, 1000)
		if (app.globalData.userInfo) {
			this.setData({
				userInfo: app.globalData.userInfo
			})
		} else {
			// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
			// 所以此处加入 callback 以防止这种情况
			// 给app.js 定义一个方法。
			app.userInfoReadyCallback = res => {
				app.globalData.userInfo = res.userInfo
				this.setData({
					userInfo: res.userInfo
				})
			}
		}
		// this.getList()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		for (let i = 0; i < this.data.list.length; i++) {
			let v = wx.createVideoContext('v' + i)
			v.seek(0)
			v.pause()
		}

		this.goodSee();
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		return {
			path: '/pages/index/index',
			imageUrl: '/image/sharel.png'
		}
	},
	goCenter: function(e) {
		var pages = getCurrentPages() //获取加载的页面
		var currentPage = pages[pages.length - 1] //获取当前页面的对象
		var url = currentPage.route //当前页面url
		var targetPage = e.currentTarget.dataset.url.substring(1)
		if (url != targetPage) {
			wx.navigateTo({
				url: '/' + targetPage
			})
		}
	},
	goIndex: function(e) {
		wx.redirectTo({
			url: '/pages/index/index'
		})
	},
	my: function(r) {
		var _this = this
		if (r.detail.errMsg == 'getUserInfo:ok') {
			app.globalData.userInfo = r.detail.userInfo
			wx.request({
				url: app.globalData.url+'/v1/wechat/user',
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				data: {
					nikname: r.detail.userInfo.nickName,
					headimgurl: r.detail.userInfo.avatarUrl,
					openid: app.globalData.openId
				},
				success: function(r) {
					if (r.data.code == 0) {
						wx.navigateTo({
							url: '/pages/center/center',
						})
					}
				}
			})
		}
	}
})
